<template>
  <a-modal
    title="Apply for After-Sales Service"
    :open="open"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :confirmLoading="loading"
    :width="modalWidth"
    class="after-sale-modal modal-container"
    :maskClosable="true"
    :destroyOnClose="true"
  >
    <!-- 商品信息区域 -->
    <div class="product-info" v-if="item">
      <div class="product-card">
        <div class="product-image">
          <img :src="item.image" alt="Product Image" />
        </div>
        <div class="product-details">
          <div class="product-name">{{ item.goods_name }}</div>
          <div class="product-spec">
            Specification: 
            <template v-if="item && item.spec_text">
              <template v-if="parseSpecText(item.spec_text).size">
                {{ parseSpecText(item.spec_text).size }}
              </template>
              <template v-if="parseSpecText(item.spec_text).imageUrl">
                <span class="color-image-container" v-if="parseSpecText(item.spec_text).imageUrl">
                  <img :src="parseSpecText(item.spec_text).imageUrl" alt="Color" class="color-image"/>
                </span>
              </template>
              <template v-if="!parseSpecText(item.spec_text).size && !parseSpecText(item.spec_text).imageUrl">
                {{ item.spec_text || 'Default Specification' }}
              </template>
            </template>
            <template v-else>Default Specification</template>
          </div>
          <div class="product-price">
            <span>Unit Price: ¥{{ item.price }}</span>
            <span class="quantity">Quantity: {{ item.num }}</span>
          </div>
          <div class="refundable-amount">
            Refundable Amount: <span class="amount">¥{{ maxAmount }}</span>
          </div>
        </div>
      </div>
    </div>

    <a-divider />

    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      layout="vertical"
      class="form-container"
    >
      <a-form-item label="After-Sales Type" name="refund_type" class="form-item">
        <a-radio-group v-model:value="formState.refund_type">
          <a-radio :value="1">Return and Refund</a-radio>
          <a-radio :value="2">Exchange</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="Refund Quantity" name="refund_num" class="form-item">
        <a-input-number
          v-model:value="formState.refund_num"
          :min="1"
          :max="maxQuantity"
          style="width: 100%"
        />
      </a-form-item>

      <a-form-item v-if="formState.refund_type === 1" label="Refund Amount" name="apply_money" class="form-item">
        <a-input-number
          v-model:value="formState.apply_money"
          :min="0.01"
          :max="maxAmount"
          :precision="2"
          style="width: 100%"
          :formatter="value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
          :parser="value => value.replace(/\¥\s?|(,*)/g, '')"
        />
      </a-form-item>

      <a-form-item label="Application Description" name="remark" class="form-item">
        <a-textarea
          v-model:value="formState.remark"
          placeholder="Describe clearly to help the merchant process the after-sales problem quickly"
          :rows="4"
          class="form-textarea"
        />
      </a-form-item>

      <a-form-item label="Upload Proof (Up to 6 photos)" name="remark_images" class="form-item">
        <a-upload
          v-model:fileList="fileList"
          list-type="picture-card"
          :before-upload="beforeUpload"
          @preview="handlePreview"
          @remove="handleRemove"
          :maxCount="6"
          class="image-upload upload-list-inline"
        >
          <div v-if="fileList.length < 6">
            <plus-outlined />
            <div style="margin-top: 8px">Upload Image</div>
          </div>
        </a-upload>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, onBeforeUnmount } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  order: {
    type: Object,
    default: null
  },
  item: {
    type: Object,
    default: null
  }
});

const emit = defineEmits(['update:open', 'submit']);

const formRef = ref(null);
const loading = ref(false);
const fileList = ref([]);

// 表单数据
const formState = reactive({
  id: 0,
  detail_id: 0,
  refund_type: 1,
  refund_num: 1,
  apply_money: 0,
  remark: '',
  remark_images: ''
});

// 表单验证规则
const rules = {
  refund_type: [{ required: true, message: 'Please select the after-sales type' }],
  refund_num: [{ required: true, message: 'Please enter the refund quantity' }],
  apply_money: [{ required: true, message: 'Please enter the refund amount' }],
  remark: [{ required: true, message: 'Please enter the application description' }]
};

// 计算最大数量
const maxQuantity = computed(() => {
  return props.item?.num || 0;
});

// 计算最大金额
const maxAmount = computed(() => {
  return props.item ? parseFloat(props.item.price) * props.item.num : 0;
});

// Add window width tracking
const windowWidth = ref(window.innerWidth);
const modalWidth = computed(() => {
  if (windowWidth.value <= 576) {
    return '95%';
  } else if (windowWidth.value <= 768) {
    return '85%';
  } else {
    return '600px';
  }
});

// Add window resize handler
const handleResize = () => {
  windowWidth.value = window.innerWidth;
};

onMounted(() => {
  window.addEventListener('resize', handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});

// 解析规格文本
const parseSpecText = (specText) => {
  if (!specText) return { size: '', imageUrl: '' };
  
  // 检查是否包含图片URL和尺寸 - 第一种情况
  if (specText.includes('http') && specText.includes('，')) {
    const parts = specText.split('，');
    return {
      imageUrl: parts[0],
      size: parts[1] || ''
    };
  }
  
  // 检查是否只有图片URL - 第二种情况
  if (specText.includes('http')) {
    return {
      imageUrl: specText,
      size: ''
    };
  }
  
  // 只有尺寸 - 第三种情况
  return {
    imageUrl: '',
    size: specText
  };
};

// 监听可见性变化
watch(() => props.open, (val) => {
  if (val) {
    formState.id = props.order?.id || 0;
    formState.detail_id = props.item?.id || 0;
    formState.refund_num = props.item?.num || 1;
    formState.apply_money = props.item ? (parseFloat(props.item.price) * props.item.num).toFixed(2) : 0;
    fileList.value = [];
  }
});

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate();
    
    if (!formState.remark) {
      message.error('Please fill in the application description');
      return;
    }
    
    // 处理图片上传
    const images = fileList.value.map(file => file.url || file.response?.url).filter(Boolean);
    formState.remark_images = images.join(',');
    
    loading.value = true;
    emit('submit', { ...formState });
  } catch (error) {
    console.error('Form validation failed:', error);
  }
};

// 处理取消
const handleCancel = () => {
  emit('update:open', false);
};

// 上传前处理
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('Only image files can be uploaded!');
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('The image size cannot exceed 2MB!');
    return false;
  }
  return true;
};

// 处理预览
const handlePreview = async (file) => {
  if (!file.url && !file.preview) {
    file.preview = await getBase64(file.originFileObj);
  }
  window.open(file.url || file.preview);
};

// 处理删除
const handleRemove = (file) => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
};

// 获取图片base64
const getBase64 = (file) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
};
</script>

<style scoped>
.after-sale-modal {
  width: 100%;
  max-width: 100%;
  overflow-x: hidden;
}

.form-container {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
  margin-bottom: 20px;
}

.form-item {
  margin-bottom: 16px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
}

.form-textarea {
  width: 100%;
}

.image-upload {
  margin-top: 10px;
}

.upload-list-inline :deep(.ant-upload-list-item) {
  float: left;
  width: 100px;
  margin-right: 8px;
}

.upload-list-inline :deep(.ant-upload-animate-inline-appear) {
  animation-duration: 0s;
}

.product-info {
  margin-bottom: 16px;
}

.product-card {
  display: flex;
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 12px;
  background-color: #fafafa;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 12px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
  flex-shrink: 0;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-details {
  flex: 1;
  min-width: 0;
}

.product-name {
  font-weight: bold;
  margin-bottom: 6px;
  color: #333;
  font-size: 14px;
  word-break: break-word;
}

.product-spec {
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.product-price {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-bottom: 6px;
  flex-wrap: wrap;
}

.quantity {
  margin-left: 12px;
}

.refundable-amount {
  font-size: 14px;
  color: #666;
}

.amount {
  font-weight: bold;
  color: #ff4d4f;
  font-size: 16px;
}

.color-image-container {
  display: inline-block;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  overflow: hidden;
  margin-left: 8px;
  border: 1px solid #eee;
  vertical-align: middle;
  flex-shrink: 0;
}

.color-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* Improved close button styles */
:deep(.ant-modal-close) {
  padding: 8px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  width: 36px;
  height: 36px;
  top: 8px;
  right: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-modal-close-x) {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  font-size: 16px;
}

/* Responsive styles */
@media (max-width: 768px) {
  .modal-container :deep(.ant-modal-content) {
    width: 100%;
    margin: 0;
    padding: 16px;
  }
  
  .modal-container :deep(.ant-modal-body) {
    padding: 12px;
  }
  
  :deep(.ant-form-item) {
    margin-bottom: 12px;
  }
  
  .form-item {
    margin-bottom: 12px;
  }
  
  .form-container {
    max-height: 70vh;
  }
  
  .upload-list-inline :deep(.ant-upload-list-item) {
    width: 80px;
    margin-right: 6px;
    margin-bottom: 6px;
  }
  
  :deep(.ant-radio-group) {
    display: flex;
    flex-direction: column;
  }
  
  :deep(.ant-radio-wrapper) {
    margin-right: 0;
    margin-bottom: 8px;
  }
  
  .modal-container :deep(.ant-modal-close) {
    width: 36px;
    height: 36px;
    z-index: 999;
  }
  
  /* Add custom styles for footer buttons to make them more accessible */
  .modal-container :deep(.ant-modal-footer .ant-btn) {
    height: 40px;
    font-size: 14px;
    min-width: 80px;
  }
  
  .product-card {
    flex-direction: column;
  }
  
  .product-image {
    margin-bottom: 12px;
    margin-right: 0;
    width: 60px;
    height: 60px;
  }
}

@media (max-width: 576px) {
  .modal-container :deep(.ant-modal) {
    max-width: 100% !important;
    margin: 0;
    top: 0;
  }
  
  .modal-container :deep(.ant-modal-content) {
    border-radius: 0;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .modal-container :deep(.ant-modal-body) {
    flex: 1;
    overflow-y: auto;
    padding: 12px;
  }
  
  .modal-container :deep(.ant-modal-header) {
    padding: 12px 16px;
  }
  
  .modal-container :deep(.ant-modal-title) {
    font-size: 16px;
  }
  
  .modal-container :deep(.ant-modal-footer) {
    border-top: 1px solid #f0f0f0;
    padding: 10px 16px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .form-container {
    max-height: calc(100vh - 120px);
    overflow-y: auto;
    padding-right: 5px;
  }
  
  .upload-list-inline :deep(.ant-upload-list-item) {
    width: 70px;
    margin-right: 4px;
  }
  
  .upload-list-inline :deep(.ant-upload-select) {
    width: 70px !important;
    height: 70px !important;
  }
  
  .modal-container :deep(.ant-modal-close) {
    position: fixed;
    z-index: 1001;
    background: rgba(255, 255, 255, 0.9);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
  
  .product-spec, .product-price {
    font-size: 11px;
  }
  
  .amount {
    font-size: 14px;
  }
}
</style> 